// pages/dataupload/dataupload.js
import Message from 'tdesign-miniprogram/message/index';
var app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    patient_id: null,
    role: '',
    fileType: '',
    fileTypeVisible: false,
    filePathValue: '',
    fileTypes: [{
      label: '小贝壳',
      value: '小贝壳'
    },{
      label: '瞬感',
      value: '瞬感'
    }],
    glucoseError: false,
    highSugar: 0,
    lowSugar: 0,

    fingerSugar: null,
    type: null,
    recordTime: null,

    mode: '',
    minute: null,
    types: [{
        label: '空腹',
        value: '空腹'
      },
      {
        label: '早餐后',
        value: '早餐后'
      },
      {
        label: '上午加餐',
        value: '上午加餐'
      },
      {
        label: '午餐前',
        value: '午餐前'
      },
      {
        label: '午餐后',
        value: '午餐后'
      },
      {
        label: '下午加餐',
        value: '下午加餐'
      },
      {
        label: '晚餐前',
        value: '晚餐前'
      },
      {
        label: '晚餐后',
        value: '晚餐后'
      },
      {
        label: '晚间加餐',
        value: '晚间加餐'
      },
      {
        label: '睡前',
        value: '睡前'
      },
      {
        label: '夜间',
        value: '夜间'
      }
    ],
    fileName: "未选择文件",
    sid: "",
    valueColName: "",
    timeColName: "",
  },
  onGlucoseInput(e) {
    const {
      glucoseError
    } = this.data;
    const isNumber = /^\d+(\.\d+)?$/.test(e.detail.value);
    if (glucoseError === isNumber) {
      this.setData({
        glucoseError: !isNumber,
      });
    }
    if (isNumber === true) {
      this.setData({
        fingerSugar: parseFloat(e.detail.value)
      })
    } else {
      this.setData({
        fingerSugar: e.detail.value
      })
    }
  },
  showPicker(e) {
    const {
      mode
    } = e.currentTarget.dataset;
    this.setData({
      mode,
      [`${mode}Visible`]: true,
      minute: new Date().getHours().toString() + ':' + new Date().getMinutes().toString()
    });
  },
  hidePicker() {
    const {
      mode
    } = this.data;
    this.setData({
      [`${mode}Visible`]: false,
    });
  },
  onConfirm(e) {
    const {
      value
    } = e.detail;
    const {
      mode
    } = this.data;

    this.setData({
      [mode]: value,
      [`${mode}Text`]: value,
      recordTime: Date.parse(new Date(new Date().setHours(parseInt(value.toString().substr(0, 2)), parseInt(value.toString().substr(3, 2)), 0))) / 1000
    });
    this.hidePicker();
  },

  onPickerChange(e) {
    const {
      key
    } = e.currentTarget.dataset;
    const {
      value
    } = e.detail;

    console.log('picker change:', e.detail.value[0]);
    this.setData({
      [`${key}Visible`]: false,
      [`${key}Value`]: value,
      [`${key}`]: e.detail.value[0]
    });
  },

  onPickerCancel(e) {
    const {
      key
    } = e.currentTarget.dataset;
    // console.log(e, '取消');
    // console.log('picker1 cancel:');
    this.setData({
      [`${key}Visible`]: false,
    });
  },

  onTypePicker(e) {
    const {
      mode
    } = e.currentTarget.dataset;
    this.setData({
      [`${mode}Visible`]: true
    });
  },

  submitByHand() {
    var fingerSugar = this.data.fingerSugar;
    var glucoseError = this.data.glucoseError;
    var recordTime = this.data.recordTime;
    var type = this.data.type;
    if (glucoseError == true) {
      Message.warning({
        context: this,
        offset: [0, 0],
        duration: 2500,
        content: '血糖值格式错误',
      });
      return;
    } else if (fingerSugar == null) {
      Message.warning({
        context: this,
        offset: [0, 0],
        duration: 2500,
        content: '血糖值不可为空',
      });
      return;
    } else if (fingerSugar == 0.0) {
      Message.warning({
        context: this,
        offset: [0, 0],
        duration: 2500,
        content: '血糖值必须大于0.0',
      });
      return;
    } else if (type == null) {
      Message.warning({
        context: this,
        offset: [0, 0],
        duration: 2500,
        content: '类型不可为空',
      });
      return;
    } else if (recordTime == null) {
      Message.warning({
        context: this,
        offset: [0, 0],
        duration: 2500,
        content: '记录时间不可为空',
      });
      return;
    }

    wx.request({ // 调用接口
      url: `${app.globalData.protocol}://${app.globalData.host}/bgmp/api/user?Action=AddBg`,
      method: 'POST',
      header: {
        "Content-Type": "application/json",
        "x-api-key": wx.getStorageSync('token')
      },
      data: {
        "time": this.data.recordTime,
        "value": this.data.fingerSugar,
        "type": this.data.type
      },
      success: (res) => { // 接口调用成功，获取token并缓存
        console.log(res);
        if (res.statusCode == 200) {
          console.log("submit successfully");
          Message.success({
            context: this,
            offset: [0, 0],
            duration: 2500,
            content: '上传成功',
          });
          setTimeout(function () {
            wx.navigateBack();
          }, 1000); // 延时 2000 毫秒（2 秒）
          // wx.switchTab({
          //     url: '/pages/bloodsugar/bloodsugar',
          // });
          // wx.showModal({
          //     title: '上传成功',
          //     confirmText: "确定",
          //     showCancel: false,
          //     success: function (res) {
          //         if (res.confirm) {
          //             //点击确定按钮重定向到血糖界面
          //             wx.switchTab({
          //               url: '/pages/bloodsugar/bloodsugar',
          //             });
          //         } else if (res.cancel) {
          //             //点击取消按钮
          //         }
          //     }
          // })
        } else {
          console.log("submit unsuccessfully");
          wx.showModal({
            title: '上传失败',
            confirmText: "确定",
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                console.log("确定");
              } else if (res.cancel) {
                //点击取消按钮
                console.log("取消");
              }
            }
          })
        }
      },
      fail() {
        console.log("submit unsuccessfully");
      }
    });
    wx.request({ // 调用接口
      url: `${app.globalData.protocol}://${app.globalData.host}/bgmp/api/user?Action=ListTags`,
      // url: 'https://124.220.110.138:443/bgmp/api/user?Action=ListTags',           
      method: 'POST',
      header: {
        "Content-Type": "application/json",
        "x-api-key": wx.getStorageSync('token')
      },
      data: {},
      success: (res) => { // 接口调用成功，获取token并缓存

        if (res.statusCode == 200) {
          console.log("submit successfully");
        } else {
          console.log("submit unsuccessfully");
        }
      },
      fail() {
        console.log("submit unsuccessfully");
      }
    });
  },
  chooseFile() {

    //使得wx函数内可以对data赋值
    var that = this;
    //选择文件
    wx.chooseMessageFile({
      count: 1, // 最多可以选择1个文件
      type: 'file', // 可选择的文件类型，这里选择任意文件类型
      success(res) {
        // console.log(res);                    
        //显示文件名
        that.setData({
          fileName: res.tempFiles[0].name,
          filePath: res.tempFiles[0].path
        })
        wx.showLoading({
          title: '上传中',
        });
        //上传文件
        wx.uploadFile({
          filePath: that.data.filePath,
          name: 'file',
          url: `${app.globalData.protocol}://${app.globalData.host}/bgmp/api/files/upload?Name=avatar`,
          method: 'POST',
          header: {
            "Content-Type": "application/json",
            "x-api-key": wx.getStorageSync('token')
          },
          success(res) {
            //文件上传成功
            console.log('sugar blood file unload successfully', res)
            if (res.statusCode == 200) {
              var data = JSON.parse(res.data);
              that.setData({
                sid: data.message
              })
              // 不需要这个接口了
              // //获取文件列名
              // wx.request({
              //   url: `${app.globalData.protocol}://${app.globalData.host}/bgmp/api/user?Action=SelectCols`,
              //   method: 'POST',
              //   header: {
              //     "Content-Type": "application/json",
              //     "x-api-key": wx.getStorageSync('token')
              //   },
              //   data: {
              //     "sid": that.data.sid
              //   },
              //   success(res) {
              //     //获取列名成功
              //     if (res.statusCode == 200) {
              //       var message = res.data.message;
              //       var options = [];
              //       for (var i = 0; i < message.length; i++) {
              //         options.push({
              //           value: i,
              //           label: message[i]
              //         });
              //       }
              //       that.setData({
              //         hideChooseCol: false,
              //         ['bloodsugarColumn.options']: options,
              //         ['timeColumn.options']: options,
              //         valueColName: options[1].label,
              //         timeColName: options[0].label
              //       })

              //     } else {
              //       console.log("文件解析错误", res)
              //       Message.error({
              //         context: this,
              //         offset: [0, 0],
              //         duration: 2500,
              //         content: '文件解析错误',
              //       });
              //     }
              //   },
              //   complete() {
              //     wx.hideLoading();
              //   }
              // })
            } else {
              console.log("选择文件上传错误", res)
              Message.error({
                context: this,
                offset: [0, 0],
                duration: 2500,
                content: '文件上传错误',
              });
            }
          },
          fail(res) {
            console.log("服务器错误", res)
            Message.error({
              context: this,
              offset: [0, 0],
              duration: 2500,
              content: '服务器故障，我们将尽快维修',
            });
          },
          complete() {
            wx.hideLoading();
          }
        })
      },
      fail(res) {
        console.log("选择文件出现错误", res)
        Message.error({
          context: this,
          offset: [0, 0],
          duration: 2500,
          content: '当前无法选择文件，我们将尽快维修',
        });
      }
    })
  },
  submitByFile() {
    var that = this;
    wx.showLoading({
      title: '上传中',
    });
    console.log(that.data.sid)
    // console.log(that.data.timeColName)
    // console.log(that.data.valueColName)
    const requestData = {
      "sid": that.data.sid,
      "user_id": that.data.patient_id,
      "category": that.data.fileType
    }
    console.log('requestData', requestData)
    wx.request({
      url: `${app.globalData.protocol}://${app.globalData.host}/bgmp/api/user?Action=LoadDataFromSpecificFile`,
      method: 'POST',
      header: {
        "Content-Type": "application/json",
        "x-api-key": wx.getStorageSync('token')
      },
      data: requestData,
      success(res) {
        if (res.statusCode == 200) {
          console.log(res)
          Message.success({
            context: this,
            offset: [0, 0],
            duration: 2500,
            content: '数据上传成功',
          });
          setTimeout(function () {
            wx.navigateBack();
          }, 1000);
          // wx.navigateBack();
          // wx.switchTab({
          //     url: '/pages/bloodsugar/bloodsugar',
          // });

        } else {
          Message.error({
            context: this,
            offset: [0, 0],
            duration: 2500,
            content: '数据上传失败',
          });
        }
      },
      complete() {
        wx.hideLoading();
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const role = wx.getStorageSync('role')
    console.log("options", options)
    console.log("role", role === 'patient')
    this.setData({
      patient_id: parseInt(options.patient_id),
      role: role
    })
    console.log('patient_id', this.data.patient_id)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.setData({
      minute: new Date().getHours().toString() + ':' + new Date().getMinutes().toString()
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})